<template>
  <a-card>
    <template #title>
      <a-button type="primary" @click="addList" v-permiss="['add']">添加</a-button>
    </template>
    <a-table row-key="id" :columns="tableColumn" :pagination="pagination" :data-source="tableData">
      <template #operation="{record}">
        <a-button type="link" @click="editList(record)" v-permiss="['update']">修改</a-button>
      </template>
    </a-table>

    <a-modal v-model:visible="visible.isShow" :title="visible.title" @ok="confirm"
             :afterClose="clearForm"
             width="70%"
             :maskClosable="false">
      <div style="margin-bottom: 10px">
        <a-month-picker style="width:220px" v-model:value="form.month" valueFormat="YYYY-MM" placeholder="请选择月份"
                        format="YYYY-MM"/>
        <div style="margin-top: 15px;display:flex">
          <a-upload
              accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              name="file"
              :showUploadList="false"
              :before-upload="excelFileUpload"
          >
            <a-button type="primary" style="margin-right: 15px">
              <upload-outlined></upload-outlined>
              导入
            </a-button>
          </a-upload>
          <a-button><a href="https://ddhkapps.oss-cn-hongkong.aliyuncs.com/doc/assets_template.xlsx">下载模板</a></a-button>
        </div>
      </div>
      <h2>资产信息</h2>
      <a-table row-key="value" :columns="addTableColumn1" bordered :pagination="false" :data-source="addTableData1">
        <template #title="{record}">
          <div v-html="record ?  record.title : ''"></div>
        </template>
        <template #value="{record,index}">
          <a-input style="width:100%" @change="changeValueComputed(index)" v-model:value="form[record.value]"/>
        </template>
      </a-table>
      <h2 style="margin:15px 0">负债和所有者（或股东）权益 信息</h2>
      <a-table row-key="value" :columns="addTableColumn2" bordered :pagination="false" :data-source="addTableData2">
        <template #title="{record}">
          <div v-html="record ?  record.title : ''"></div>
        </template>
        <template #value="{record,index}">
          <a-input style="width:100% " @change="changeAssetsValueComputed(index)" v-model:value="form[record.value]"/>
        </template>
      </a-table>
    </a-modal>
  </a-card>
</template>

<script>
import {ref, onMounted, reactive, computed, toRefs, h} from 'vue'
import {importProfitAssets, increaseProfitAssets, fetchProfitAssetsList, updateProfitAssets} from '../../../api/finance'
import {message} from "ant-design-vue";
import XLSX from "xlsx"
import {UploadOutlined} from "@ant-design/icons-vue";

const tableColumn = [
  {title: '日期', dataIndex: 'month', width: 150, align: 'center'},
  {title: '更新时间', dataIndex: 'updateTime', width: 150, align: 'center'},
  {title: '操作', width: 100, align: 'center', slots: {customRender: 'operation',}},
]

const addTableData1 = [
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '货币资金', value: 'monetaryCapital'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '交易性金融资产', value: 'tradingFinancialAssets'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '应收票据', value: 'notesReceivable'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '应收账款', value: 'accountsReceivable'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '预付款项', value: 'advancePayment'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '应收利息', value: 'interestReceivable'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '应收股利', value: 'dividendsReceivable'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '其他应收款', value: 'otherReceivables'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '存货', value: 'stock'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '一年内到期的非流动资产', value: 'yearNonCurrentAssets'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '其他流动资产', value: 'otherCurrentAssets'},
  {oneTitle: '资产', twoTitle: '流动资产', threeTitle: '流动资产合计', value: 'totalCurrentAssets'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '可供出售金融资产', value: 'availableForSaleFinancialAssets'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '持有至到期投资', value: 'heldToMaturityInvestment'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '长期应收款', value: 'longTermReceivables'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '长期股权投资', value: 'longTermEquityInvestment'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '投资性房地产', value: 'investmentRealEstate'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '固定资产', value: 'fixedAssets'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '在建工程', value: 'constructionInProgress'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '工程物资', value: 'engineeringMaterials'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '固定资产清理', value: 'liquidationOfFixedAssets'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '生产性生物资产', value: 'productiveBiologicalAssets'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '油气资产', value: 'oilAndGasAssets'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '无形资产', value: 'intangibleAssets'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '开发支出', value: 'developmentExpenditure'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '商誉', value: 'goodwill'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '长期待摊费用', value: 'longTermDeferredExpenses'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '递延所得税资产', value: 'deferredTaxAssets'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '其他非流动资产', value: 'otherNonCurrentAssets'},
  {oneTitle: '资产', twoTitle: '非流动资产', threeTitle: '非流动资产合计', value: 'totalNonCurrentAssets'},
  {oneTitle: '资产总计 [ = 流动资产合计 + 非流动资产合计 ]', value: 'totalAssets'},
]
const addTableColumn1 = [
  {
    title: '一级科目名称', dataIndex: 'oneTitle', align: 'center', customRender: ({text, index}) => {
      const renderObj = {
        children: text,
        props: {},
      }
      if (text === '资产') {
        renderObj.props.rowSpan = index === 0 ? 30 : 0
      } else if (index === 30) {
        renderObj.props.colSpan = 3
      }
      return renderObj
    }
  },
  {
    title: '二级科目名称', dataIndex: 'twoTitle', align: 'center', customRender: ({text, index}) => {
      const renderObj = {
        children: text,
        props: {},
      }
      if (text === '流动资产') {
        renderObj.props.rowSpan = index === 0 ? 12 : 0
      } else if (text === '非流动资产') {
        renderObj.props.rowSpan = index === 12 ? 18 : 0
      } else if (index === 30) {
        renderObj.props.colSpan = 0
      }
      return renderObj
    }
  },
  {
    title: '三级科目名称', dataIndex: 'threeTitle', align: 'center', customRender: ({text, index}) => {
      const renderObj = {
        children: text,
        props: {},
      }
      if (index === 30) {
        renderObj.props.colSpan = 0
      }
      return renderObj
    }
  },
  {title: '参数', dataIndex: 'value', align: 'center', slots: {customRender: 'value',}},
]

const addTableData2 = [
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '短期借款', value: 'shortTermLoans'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '交易性金融负债', value: 'tradingFinancialLiabilities'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '应付票据', value: 'notesPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '应付账款', value: 'accountsPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '预收款项', value: 'advancePaymentLiabilities'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '应付职工薪酬', value: 'employeeCompensationPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '应交税费', value: 'taxPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '应付利息', value: 'interestPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '应付股利', value: 'dividendsPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '其他应付款', value: 'otherAccountsPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '一年内到期的非流动负债', value: 'yearNonCurrentLiabilities'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '其他流动负债', value: 'otherCurrentLiabilities'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '流动负债', threeTitle: '流动负债合计', value: 'totalCurrentLiabilities'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '非流动负债', threeTitle: '长期借款', value: 'longTermLoan'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '非流动负债', threeTitle: '应付债券', value: 'bondsPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '非流动负债', threeTitle: '长期应付款', value: 'longTermAccountsPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '非流动负债', threeTitle: '专项应付款', value: 'specialAccountsPayable'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '非流动负债', threeTitle: '预计负债', value: 'estimatedLiabilities'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '非流动负债', threeTitle: '递延所得税负债', value: 'deferredTaxLiability'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '非流动负债', threeTitle: '其他非流动负债', value: 'otherNonCurrentLiabilities'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '非流动负债', threeTitle: '非流动负债合计', value: 'totalNonCurrentLiabilities'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '负债合计 [ = 流动负债合计 + 非流动负债合计]', value: 'totalLiabilities'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '所有者（或股东）权益', threeTitle: '实收资本（或股本）', value: 'paidInCapital'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '所有者（或股东）权益', threeTitle: '资本公积', value: 'capitalReserve'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '所有者（或股东）权益', threeTitle: '减：库存股', value: 'treasuryStock'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '所有者（或股东）权益', threeTitle: '盈余公积', value: 'surplusReserve'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '所有者（或股东）权益', threeTitle: '未分配利润', value: 'undistributedProfit'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '所有者（或股东）权益', threeTitle: '其他综合收益', value: 'otherComprehensiveIncome'},
  {oneTitle: '负债和所有者（或股东）权益', twoTitle: '所有者（或股东）权益', threeTitle: '所有者权益（或股东权益）合计', value: 'totalOwnerEquity'},
  {oneTitle: '负债和所有者权益（或股东权益）总计 [= 负债合计 + 所有者权益（或股东权益）合计]', value: 'totalLiabilitiesAndOwnerEquity'},
]
const addTableColumn2 = [
  {
    title: '一级科目名称', dataIndex: 'oneTitle', align: 'center', customRender: ({text, index}) => {
      const renderObj = {
        children: text,
        props: {},
      }
      if (text === '负债和所有者（或股东）权益') {
        renderObj.props.rowSpan = index === 0 ? 29 : 0
      } else if (index === 29) {
        renderObj.props.colSpan = 3
      }
      return renderObj
    }
  },
  {
    title: '二级科目名称', dataIndex: 'twoTitle', align: 'center', customRender: ({text, index}) => {
      const renderObj = {
        children: text,
        props: {},
      }
      if (text === '流动负债') {
        renderObj.props.rowSpan = index === 0 ? 13 : 0
      } else if (text === '非流动负债') {
        renderObj.props.rowSpan = index === 13 ? 8 : 0
      } else if (text === '所有者（或股东）权益') {
        renderObj.props.rowSpan = index === 22 ? 7 : 0
      } else if (index === 21) {
        renderObj.props.colSpan = index === 21 ? 2 : 0
      } else if (index === 29) {
        renderObj.props.colSpan = 0
      }
      return renderObj
    }
  },
  {
    title: '三级科目名称', dataIndex: 'threeTitle', align: 'center', customRender: ({text, index}) => {
      const renderObj = {
        children: text,
        props: {},
      }
      if (index === 29) {
        renderObj.props.colSpan = 0
      } else if (index === 21) {
        renderObj.props.colSpan = 0
      }
      return renderObj
    }
  },
  {title: '参数', dataIndex: 'value', align: 'center', slots: {customRender: 'value',}},
]
console.log(addTableData2)
export default {
  name: "AssetsManage",
  components: {
    UploadOutlined
  },
  setup() {
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      visible: {
        isShow: false,
        title: '',
        type: ''
      },
      form: {
        month: null
      },

    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + '条',
      onChange: (page) => {
        state.page.pageNum = page
        getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        getTableData()
      }
    }))

    async function getTableData() {
      const businessId = sessionStorage.getItem('businessValue')
      if (!businessId) return message.error('请选择事业部')
      const res = await fetchProfitAssetsList({
        ...state.page,
        businessId: parseInt(businessId)
      })
      if (res.code === 200) {
        const {list, total} = res.data
        state.tableData = list
        state.page.total = total
      }
    }


    function addList() {
      state.visible = {
        isShow: true,
        type: 'add',
        title: '添加'
      }
    }

    function editList(record) {
      state.form = {...record}
      state.visible = {
        isShow: true,
        type: 'update',
        title: '修改'
      }
    }

    function clearForm() {
      state.form = {
        month: null
      }
    }

    function changeValueComputed(index) {
      if (index >= 0 && index <= 10) {
        setTotalCurrentAssets()
      }
      if (index >= 12 && index <= 28) {
        setTotalNonCurrentAssets()
      }

      if (index >= 12 && index <= 28) {
        setTotalNonCurrentAssets()
      }
      setTotalAssets()
    }
    // 负债和所有者（或股东）权益 信息
    function changeAssetsValueComputed (index) {
      if (index >= 0 && index <= 11) {
        setTotalCurrentLiabilities()
      }
      if (index >= 13 && index <= 19) {
        setTotalNonCurrentLiabilities()
      }
      if (index >= 22 && index <= 27) {
        setTotalOwnerEquity()
      }
      setTotalLiabilities()
      setTotalLiabilitiesAndOwnerEquity()
    }
    // 流动资产合计
    function setTotalCurrentAssets() {
      let arrValue = []
      addTableData1.forEach((item, index) => {
        if (index >= 0 && index <= 10) {
          const value = state.form[addTableData1[index].value]
          if (value) {
            arrValue.push(parseFloat(value || 0))
          }
        }
      })
      state.form['totalCurrentAssets'] = arrValue.reduce(((previousValue, currentValue) => {
        return previousValue + currentValue
      })).toFixed(2)
    }

    // 非流动资产合计
    function setTotalNonCurrentAssets() {
      let arrValue = []
      addTableData1.forEach((item, index) => {
        if (index >= 12 && index <= 28) {
          const value = state.form[addTableData1[index].value]
          if (value) {
            arrValue.push(parseFloat(value || 0))
          }
        }
      })
      state.form['totalNonCurrentAssets'] = arrValue.reduce(((previousValue, currentValue) => {
        return previousValue + currentValue
      })).toFixed(2)
    }

    // 资产总计
    function setTotalAssets() {
      const d14 = parseFloat(state.form[addTableData1[11].value] || 0)
      const d32 = parseFloat(state.form[addTableData1[29].value] || 0)
      const value = (d14 + d32).toFixed(2)
      state.form['totalAssets'] = value
    }
    // 流动负债合计
    function setTotalCurrentLiabilities() {
      let arrValue = []
      addTableData2.forEach((item, index) => {
        if (index >= 0 && index <= 11) {
          const value = state.form[addTableData2[index].value]
          if (value) {
            arrValue.push(parseFloat(value || 0))
          }
        }
      })
      state.form['totalCurrentLiabilities'] = arrValue.reduce(((previousValue, currentValue) => {
        return previousValue + currentValue
      })).toFixed(2)
    }

    // 非流动负债合计
    function setTotalNonCurrentLiabilities() {
      let arrValue = []
      addTableData2.forEach((item, index) => {
        if (index >= 0 && index <= 11) {
          const value = state.form[addTableData2[index].value]
          if (value) {
            arrValue.push(parseFloat(value || 0))
          }
        }
      })
      state.form['totalNonCurrentLiabilities'] = arrValue.reduce(((previousValue, currentValue) => {
        return previousValue + currentValue
      })).toFixed(2)
    }
    // 负债合计
    function setTotalLiabilities() {
      const d48 = parseFloat(state.form[addTableData1[12].value] || 0)
      const d56 = parseFloat(state.form[addTableData1[20].value] || 0)
      const value = (d48 + d56).toFixed(2)
      state.form['totalLiabilities'] = value
    }
    // 所有者权益（或股东权益）合计
    function setTotalOwnerEquity() {
      let arrValue = []
      addTableData2.forEach((item, index) => {
        if (index >= 22 && index <= 27) {
          const value = state.form[addTableData2[index].value]
          if (value) {
            arrValue.push(parseFloat(value || 0))
          }
        }
      })
      state.form['totalOwnerEquity'] = arrValue.reduce(((previousValue, currentValue) => {
        return previousValue + currentValue
      })).toFixed(2)
    }
    // 负债和所有者权益（或股东权益）总计 [= 负债合计 + 所有者权益（或股东权益）合计]
    function setTotalLiabilitiesAndOwnerEquity() {
      const d57 = parseFloat(state.form[addTableData2[21].value] || 0)
      const d64 = parseFloat(state.form[addTableData2[28].value] || 0)
      const value = (d57 + d64).toFixed(2)
      state.form['totalLiabilitiesAndOwnerEquity'] = value
    }
    function excelFileUpload(file) {
      let reader = new FileReader()
      reader.onload = async (e) => {
        let bstr = e.target.result;
        let wb = XLSX.read(bstr, {type: 'binary', cellDates: true});
        let wsname = wb.SheetNames[0];
        let ws = wb.Sheets[wsname];
        let data = XLSX.utils.sheet_to_json(ws, {header: 1});
        if (data.length > 0) {
          try {
            const tbData = [...addTableData1, ...addTableData2]
            const dataValue = data.filter((item, index) => {
              return [0, 1, 33, 34].indexOf(index) === -1
            })
            const keys = {}
            dataValue.forEach((item, index) => {
              if (item.length >= 4) {
                keys[tbData[index].value] = item[3]
              }
            })
            state.form = {
              ...state.form,
              ...keys,
            }
            message.success('导入成功')
          } catch (e) {
            message.error('导入失败 ' + e)
          }
        }

      }
      reader.readAsBinaryString(file);
    }

    async function confirm() {
      console.log(state.form)
      if (!state.form.month) {
        return message.error('请选择月份')
      }
      const isAdd = state.visible.type === 'add'
      const api = (params) => isAdd ? increaseProfitAssets(params) : updateProfitAssets(params)
      const res = await api({
        ...state.form,
        businessId: parseInt(sessionStorage.getItem('businessValue'))
      })
      if (res.code === 200) {
        message.success(isAdd ? '添加成功' : '修改成功')
        getTableData()
        state.visible.isShow = false
      }
    }

    onMounted(() => {
      getTableData()
    })
    return {
      changeValueComputed,
      excelFileUpload,
      changeAssetsValueComputed,
      addTableData1,
      addTableColumn1,
      addTableColumn2,
      addTableData2,
      pagination,
      tableColumn,
      clearForm,
      confirm,
      addList,
      editList,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
